<template>
  <div class="tw-libtagfilter" ref="tagfilters"
    :class="{xopen: open || !isFold}">
    <label v-if="title"
      class="tw-libtagfilter-label"
      :style="{width: labelWidth}">{{title}}:</label>
    <div ref="tag-box"
      class="tw-libtagfilter-tags">
      <a class="tw-libtag xfilter"
        :class="{xactive: value.length===0}"
        v-if="multiple && multipleBtnVisible"
        @click="$emit('change',[])">
        <span>全部</span>
      </a>

      <a class="tw-libtag xfilter"
        v-for="(tag, idx) in options" :style="{display: !useMorePopper ? 'inline-block' : ((curIndex > idx) ? 'inline-block' : 'none')}"
        :class="{xactive: multiple ? value.includes(tag.value):value===tag.value}"
        :key="tag.value"
        @click="clickTag(tag)">
        <span>{{tag.label}}</span>
      </a>

      <a class="tw-libtag xmore" :id="moreId" :class="{xfilter: icons.length === 0}"
        v-if="useMorePopper && curIndex < options.length"
        @click="clickMore">
        <!-- <img :src="`${$twApp.fileBaseUrl}${icons[0].localPath}`"
          :style="{width: imgWidth, height: imgHeight, objectFit: objectFit}"
          v-if="icons.length > 0 && icons[0].localPath"> -->
        <img class="xicon"
          :style="{width: imgWidth, height: imgHeight, objectFit: objectFit}"
          v-if="getIcons('default')"
          :src="`${$twApp.fileBaseUrl}${getIcons('default')}`" />
        <img class="xhovericon"
          v-if="getIcons('hover')"
          :style="{width: imgWidth, height: imgHeight, objectFit: objectFit}"
          :src="`${$twApp.fileBaseUrl}${getIcons('hover')}`" />
        <!-- <i class="el-icon-edit-outline"></i> -->
        <span v-else>更多...</span>
      </a>

      <a v-if="isFold && showToggleBtn"
        class="tw-ico xtftoggle"
        :class="{xopen: open}"
        @click="open=!open"></a>
    </div>
  </div>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'

export default {
  name: 'lib-tag-filter',

  model: {
    prop: 'value',
    event: 'change'
  },

  mixins: [style],

  props,

  data() {
    return {
      showToggleBtn: false,
      open: false,
      curIndex: this.options.length,
      widthList: []
    }
  },

  computed: {
    style () {
      return {
        boldLabel: this.boldLabel,
        selectedTagActiveBg: this.selectedTagActiveBg,
        selectedTagActiveColor: this.selectedTagActiveColor,
        useMorePopper: this.useMorePopper
      }
    }
  },

  methods: {
    getIcons (type) {
      if (type === 'default') {
        return this.icons[0] && this.icons[0].localPath ? this.icons[0].localPath : ''
      } else {
        return this.icons[1] && this.icons[1].localPath ? this.icons[1].localPath : '' ||
          (this.icons[0] && this.icons[0].localPath ? this.icons[0].localPath : '')
      }
    },
    /**
     * 功能: 初始化是否显示切换按钮及选中状态等
     */
    init () {
      this.$nextTick(() => {
        if (this.$refs['tag-box'].offsetHeight > this.toggleHeight) {
          this.showToggleBtn = true
        }
      })
    },

    /**
     * 功能: 点击标签处理
     * @param {Object} tag 标签对应的数据对象
     */
    clickTag (tag) {
      if (this.multiple) {
        // 多选处理
        if (this.value.includes(tag.value)) {
          this.value.splice(this.value.indexOf(tag.value), 1)
          this.$emit('change', this.value)
        } else {
          this.value.push(tag.value)
          this.$emit('change', this.value)
        }
      } else {
        // 单选处理
        if (this.value === tag.value) {
          if (this.toggleSelf) {
            this.$emit('change', '')
          }
        } else {
          this.$emit('change', tag.value)
        }
      }
    },

    setStyle () {
      let style = `
        ::root .tw-libtag.xfilter.xactive,
        ::root .tw-libtag.xfilter:hover {
          color: ${this.selectedTagActiveColor};
          background: ${this.selectedTagActiveBg};
        }

        ::root .tw-libtagfilter-label {
          font-weight: ${this.boldLabel ? '700' : '400'};
        }
      `

      if (this.useMorePopper) {
        style += `
          ::root .tw-libtagfilter-tags {
            // display: flex;
          }
        `
      }

      this.addStyle(style)
    },

    clickMore () {
      this.$emit('getmore', true)
    },
    resize () {
      let parentwidth = this.$refs.tagfilters.parentNode.offsetWidth
      let childwidth = 0
      let ctn = true
      this.widthList.forEach((item, index) => {
        childwidth += item
        if (ctn && childwidth >= parentwidth) {
          this.curIndex = (index - parseInt(this.difIndex))
          ctn = false
        }
      })

      // this.init()
      // console.log('ddd', this.curIndex)
    }
  },

  created () {
    if (this.multiple && !Array.isArray(this.value)  && !this.useHasSelected) {
      this.$emit('change', [])
    }
  },

  mounted () {
    if (this.useMorePopper) {
      this.widthList = []
      this.$nextTick(() => {
        this.$refs.tagfilters.childNodes.forEach((item, index) => {
          if (item instanceof HTMLElement && index === 0) {
            let offsetWidth = item.offsetWidth ? item.offsetWidth : 0
            let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
            let marginRight = parseInt(window.getComputedStyle(item).marginRight)
            this.widthList.push((offsetWidth + marginLeft + marginRight))
          }
        })
        this.$refs['tag-box'].childNodes.forEach((item, index) => {
          if (item instanceof HTMLElement) {
            let offsetWidth = item.offsetWidth ? item.offsetWidth : 0
            let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
            let marginRight = parseInt(window.getComputedStyle(item).marginRight)
            this.widthList.push((offsetWidth + marginLeft + marginRight))
          }
        })
      })
      // console.log(this.widthList)
      this.$nextTick(() => {
        this.resize()
      })
      window.addEventListener('resize', this.resize)
    }
  },

  beforeDestroy () {
    if (this.useMorePopper) {
      window.removeEventListener('resize', this.resize)
    }
  },

  watch: {
    options (val) {
      if (val && val.length > 0 && !this.useHasSelected) {
        if (this.multiple) {
          this.$emit('change', [val[0].value])
        } else {
          this.$emit('change', val[0].value)
        }
      }

      if (this.useMorePopper) {
        this.curIndex = this.options.length

        this.widthList = []
        this.$nextTick(() => {
          this.$refs.tagfilters.childNodes.forEach((item, index) => {
            if (item instanceof HTMLElement && index === 0) {
              let offsetWidth = item.offsetWidth ? item.offsetWidth : 0
              let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
              let marginRight = parseInt(window.getComputedStyle(item).marginRight)
              this.widthList.push((offsetWidth + marginLeft + marginRight))
            }
          })
          this.$refs['tag-box'].childNodes.forEach((item, index) => {
            if (item instanceof HTMLElement) {
              let offsetWidth = item.offsetWidth ? item.offsetWidth : 0
              let marginLeft = parseInt(window.getComputedStyle(item).marginLeft)
              let marginRight = parseInt(window.getComputedStyle(item).marginRight)
              this.widthList.push((offsetWidth + marginLeft + marginRight))
            }
          })
        })

        this.$nextTick(() => {
          this.resize()
        })
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
